<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="150px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="头像" prop="headUrl">
        <img :src="dataForm.headUrl" v-if="dataForm.id" style="width: 40px;height: 40px;">
        <img :src="dataForm.headUrl" v-if="!dataForm.id" style="width: 40px;height: 40px;">
        <el-upload
          class="upload-demo"
          :action="url"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          list-type="picture"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传png文件且大小不超过250KB</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="毕业学校" prop="school">
        <el-input v-model="dataForm.school" placeholder="毕业学校学校"></el-input>
      </el-form-item>
      <el-form-item label="性别:" prop="sex">
        <el-radio v-model="dataForm.sex" label="1">男</el-radio>
        <el-radio v-model="dataForm.sex" label="2">女</el-radio>
        <el-radio v-model="dataForm.sex" label="0">未知</el-radio>
      </el-form-item>

      <el-form-item label="支教地址 " prop="teachingAdd">
        <el-input v-model="dataForm.teachingAdd" placeholder="支教地址 "></el-input>
      </el-form-item>
      <el-form-item label="支教学校 " prop="teachingSchool">
        <el-input v-model="dataForm.teachingSchool" placeholder="支教学校 "></el-input>
      </el-form-item>
      <el-form-item label="支教年级 " prop="teachingGradel">
        <el-input v-model="dataForm.teachingGradel" placeholder="支教年级 "></el-input>
      </el-form-item>
      <el-form-item label="支教开始时间 " prop="teachingStartTime">
        <template>
          <el-date-picker
            style="width:250px;"
            v-model="dataForm.teachingStartTime"
             type="date"
            value-format="yyyy-MM-dd"
            placeholder="支教开始时间"
          ></el-date-picker>
        </template>
      </el-form-item>
      <el-form-item label="支教结束时间" prop="teachingEndTime">
        <template>
          <el-date-picker
            style="width:250px;"
            v-model="dataForm.teachingEndTime"
             type="date"
            value-format="yyyy-MM-dd"
            placeholder="支教结束时间"
          ></el-date-picker>
        </template>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        name: "",
        age: "",
        sex: "1",
        school: "",
        teachingAdd: "",
        teachingSchool: "",
        teachingGradel: "",
        teachingStartTime: "",
        teachingEndTime: "",
        headUrl:'',
        isAlive:'1',
      },
      dataRule: {
        name: [
          { required: true, message: "老师姓名不能为空", trigger: "blur" },
          { max: 12, message: "最长12个字符", trigger: "blur" }
        ],
        // age: [{ required: true, message: "年龄不能为空", trigger: "blur" }],
        sex: [
          {
            required: true,
            message: "性别不能为空",
            trigger: "blur"
          }
        ],
        school: [
          { required: true, message: "毕业学校不能为空", trigger: "blur" }
        ],
        teachingAdd: [
          { required: true, message: "支教地址 不能为空", trigger: "blur" },
          { max: 11, message: "最长11个字符", trigger: "blur" }
        ],
        teachingSchool: [
          { required: true, message: "支教学校 不能为空", trigger: "blur" }
        ],
        teachingGradel: [
          { required: true, message: "支教年级 不能为空", trigger: "blur" }
        ],
        teachingStartTime: [
          { required: true, message: "支教开始时间 不能为空", trigger: "blur" }
        ],
        teachingEndTime: [
          { required: true, message: "支教结束时间不能为空", trigger: "blur" }
        ],
      },
      url: ""
    };
  },
  mounted() {
    this.url = this.$http.adornUrl(
      `/partner/teacherinfo/upload?token=${this.$cookie.get("token")}`
    );
  },
  methods: {
    init(id) {
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/partner/teacherinfo/info/${this.dataForm.id}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.teacherInfo.name;
              this.dataForm.age = data.teacherInfo.age;
              this.dataForm.sex = data.teacherInfo.sex+'';
              this.dataForm.isAlive = data.teacherInfo.isAlive+'';
              this.dataForm.school = data.teacherInfo.school;
              this.dataForm.headUrl = data.teacherInfo.headUrl;
              this.dataForm.teachingAdd = data.teacherInfo.teachingAdd;
              this.dataForm.teachingSchool = data.teacherInfo.teachingSchool;
              this.dataForm.teachingGradel = data.teacherInfo.teachingGradel;
              this.dataForm.teachingStartTime =data.teacherInfo.teachingStartTime;
              this.dataForm.teachingEndTime = data.teacherInfo.teachingEndTime;
            }
          });
        }
      });
    },
    //上传头像
    handleAvatarSuccess(response, file, fileList) {
      this.fileList = fileList;
      this.successNum++;
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          this.$confirm("操作成功, 是否继续操作?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).catch(() => {
            this.visible = false;
          });
        }
        this.dataForm.headUrl = response.url;
      } else {
        this.$message.error(response.msg);
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/png';
      if (!isJPG) {
        this.$message.error("上传封面只能是 png格式!");
      }
      const isSize = new Promise(function(resolve, reject) {
        let width = 270;
        let height = 330;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          let valid = img.width == width && img.height == height;
          valid ? resolve() : reject();
        };
        img.src = _URL.createObjectURL(file);
      }).then(
        () => {
          return file;
        },
        () => {
          this.$message.error("上传的老师头像必须是270*330!");
          return Promise.reject();
        }
      );
      return isJPG  && isSize;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/partner/teacherinfo/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              name: this.dataForm.name,
              sex: this.dataForm.sex,
              headUrl:this.dataForm.headUrl,
              school: this.dataForm.school,
              teachingAdd: this.dataForm.teachingAdd,
              teachingSchool: this.dataForm.teachingSchool,
              teachingGradel: this.dataForm.teachingGradel,
              teachingStartTime: this.dataForm.teachingStartTime,
              teachingEndTime: this.dataForm.teachingEndTime,
              gmtCreated: this.dataForm.gmtCreated,
              gmtUpdate: this.dataForm.gmtUpdate,
              isAlive: this.dataForm.isAlive,
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
